package com.learning.security.service;

import com.learning.security.dal.dataobject.AdminRightDO;
import com.learning.security.dal.dataobject.AdminRoleRightDO;
import com.learning.security.dal.dataobject.AdminUserRoleDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private AdminRightService adminRightService;
    @Autowired
    private AdminRoleRightService adminRoleRightService;
    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Override
    public boolean hasAnyPermissions(Long userId, String... permissions) {
        if (null == permissions || permissions.length == 0) {
            return true;
        }
        // 获取当前用户的角色
        List<AdminUserRoleDO> adminUserRoleDOS = adminUserRoleService.listByUserId(userId);
        Set<Long> userRoleIds = adminUserRoleDOS.stream().map(AdminUserRoleDO::getRoleId).collect(Collectors.toSet());
        // 获取权限点的角色
        for (String permission : permissions) {
            AdminRightDO rightByPermission = adminRightService.getRightByPermission(permission);
            if (null == rightByPermission) {
                return false;
            }
            List<AdminRoleRightDO> roleRightList = adminRoleRightService.getRoleRightByRightId(rightByPermission.getId());
            return roleRightList.stream().map(AdminRoleRightDO::getRoleId).anyMatch(userRoleIds::contains);
        }
        return false;
    }
}
